#include<unistd.h>
#include<cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
using namespace std;
#define M 2
#define SIZE 1024
void Write(int fd)
{
    //子进程不停地给管道文件写内容
    string s="i am child hello linux!!\n";
    int number=0;//记录写入次数
    pid_t pid=getpid();
    char buffer[SIZE]={0};
    int i=5;
    char c='c';
    while(true)
    {
        //snprintf(buffer,sizeof(buffer),"%s-%d-%d\n",s.c_str(),pid,number);
        write(fd,&c,1);

        number++;
        cout<<number<<endl;
    }
}
void Read(int fd)
{
    //父进程不停地从管道中读内容
    char buffer[SIZE]={0};
    while(true)
    {
        //sleep(5);
    ssize_t retsize=read(fd,buffer,sizeof(buffer));
    if(retsize){
        buffer[retsize]=0;
    cout<<buffer<<endl;

    }
    else 
    {
        printf("farther read file done\n");
    }
    }
    

}
int main()
{
    int pipefd[M];//用来获取管道读写下标
    int repip=pipe(pipefd);//建立管道连接
    if(repip<0)return 1;
    pid_t id =fork();//创建子进程
    if(id<0)return 2;
    if(id==0)
    {
        //child
        close(pipefd[0]);
        Write(pipefd[1]);//子进程写  //1写 0 读
        close(pipefd[1]);
        exit(0);
    }
    //farther
    close(pipefd[1]);
    Read(pipefd[0]);//父进程读
    close(pipefd[0]);
    pid_t retpid=waitpid(id,NULL,0);//回收子进程
    if(retpid<0)return 3;
    return 0;
}